package com.hexb.core.utils;

import com.hexb.core.enums.AscColors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * @Package : com.hexb.core.utils
 * @Author : hexb
 * @Date : 2019-08-9 16:26
 */
@Slf4j
public class VersionUtils {

    /**
     * 获取当前springboot运行jar包MANIFEST.MF值
     */
    static public String manifestValue(String key) {
        try {
            String jarFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().replace("!/BOOT-INF/classes!/", "");
            if (!jarFilePath.endsWith(".jar")) {
                log.info(String.format("%s====>%s Must run in springboot jar package!", AscColors.YELLOW, AscColors.END));
                return null;
            }
            if (jarFilePath.startsWith("file:")) {
                jarFilePath = jarFilePath.substring(5);
            }
            JarFile jarFile = new JarFile(jarFilePath);
            Manifest manifest = jarFile.getManifest();
            return manifest.getMainAttributes().getValue(key);
        } catch (IOException e) {
            log.error(String.format("%s====>%s Get manifest value error!", AscColors.RED, AscColors.END), e);
        }
        return null;
    }
}
